<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 - 桌面版 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 面包屑导航 -->
      <div class="mb-6">
        <nav class="flex items-center space-x-2 text-sm text-gray-600">
          <router-link to="/home" class="hover:text-primary">首页</router-link>
          <i class="fas fa-chevron-right text-xs"></i>
          <router-link to="/orders" class="hover:text-primary">我的订单</router-link>
          <i class="fas fa-chevron-right text-xs"></i>
          <span class="text-gray-800">订单详情</span>
        </nav>
      </div>

      <!-- 页面标题 -->
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800">订单详情</h1>
        <p class="text-gray-600 mt-1">查看您的订单详细信息</p>
      </div>

      <!-- 订单详情内容 -->
      <div v-if="orderDetail" class="space-y-6">
        <!-- 订单基本信息 -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h2 class="text-lg font-semibold text-gray-800 mb-4">订单信息</h2>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label class="text-sm text-gray-600">订单号</label>
              <p class="font-mono text-sm mt-1">{{ orderDetail.orderNo }}</p>
            </div>
            <div>
              <label class="text-sm text-gray-600">下单时间</label>
              <p class="text-sm mt-1">{{ formatDate(orderDetail.createdAt) }}</p>
            </div>
            <div>
              <label class="text-sm text-gray-600">订单状态</label>
              <p class="mt-1">
                <span :class="getStatusClass(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</span>
              </p>
            </div>
            <div>
              <label class="text-sm text-gray-600">订单金额</label>
              <p class="text-lg font-bold text-primary mt-1">¥{{ orderDetail.actualAmount.toFixed(2) }}</p>
            </div>
            <div>
              <label class="text-sm text-gray-600">支付方式</label>
              <p class="text-sm mt-1">{{ getPaymentTypeText(orderDetail.paymentType) }}</p>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h2 class="text-lg font-semibold text-gray-800 mb-4">商品信息</h2>
          <div class="space-y-4">
            <div
              v-for="item in orderDetail.items"
              :key="item.id"
              class="flex items-center space-x-4 p-4 border border-gray-100 rounded-lg"
            >
              <img
                :src="getImageUrl(item.bookCover || item.cover)"
                :alt="item.bookTitle || item.title"
                class="w-20 h-24 object-cover rounded cursor-pointer"
                @click="goToBookDetail(item.bookId || item.id)"
              >
              <div class="flex-1">
                <h3 class="font-medium text-gray-800 mb-1 cursor-pointer hover:text-primary" @click="goToBookDetail(item.bookId || item.id)">{{ item.bookTitle || item.title }}</h3>
                <p class="text-sm text-gray-500 mb-2">作者：{{ item.author || item.bookAuthor || '未知' }}</p>
                <div class="flex items-center justify-between">
                  <span class="text-primary font-bold">¥{{ (item.price || item.bookPrice || 0).toFixed(2) }}</span>
                  <span class="text-sm text-gray-600">×{{ item.quantity || 1 }}</span>
                  <span class="font-medium">小计：¥{{ ((item.price || item.bookPrice || 0) * (item.quantity || 1)).toFixed(2) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div class="flex flex-col md:flex-row md:items-center md:justify-between">
            <div class="text-sm text-gray-600 mb-4 md:mb-0">
              共{{ orderDetail.items ? orderDetail.items.length : 0 }}件商品，总计：
              <span class="text-xl font-bold text-primary">
                ¥{{ orderDetail.actualAmount ? orderDetail.actualAmount.toFixed(2) : '0.00' }}
              </span>
            </div>
            <div class="flex space-x-2">
              <button
                @click="goBack"
                class="px-4 py-2 border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors"
              >
                返回订单列表
              </button>
              <button
                v-if="orderDetail.status === '0' || orderDetail.status === 0"
                @click="handleOrderAction('pay', orderDetail)"
                class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
              >
                立即付款
              </button>
              <button
                v-if="orderDetail.status === '2' || orderDetail.status === 2"
                @click="handleOrderAction('confirm', orderDetail)"
                class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
              >
                确认收货
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="loading" class="text-center py-16">
        <i class="fas fa-spinner fa-spin text-4xl text-gray-400 mb-4"></i>
        <p class="text-gray-500">正在加载订单详情...</p>
      </div>
      <div v-else class="text-center py-16">
        <p class="text-gray-500">订单不存在或已删除。</p>
      </div>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10 mt-16">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">帮助中心</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">售后服务</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送说明</a></li>
            </ul>
          </div>

          <!-- 联系我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-2 text-sm text-gray-400">
              <li><i class="fas fa-phone mr-2"></i>400-123-4567</li>
              <li><i class="fas fa-envelope mr-2"></i>service@bookstore.com</li>
              <li><i class="fas fa-map-marker-alt mr-2"></i>北京市朝阳区xxx街道</li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
          <div class="text-gray-500 text-sm mb-4 md:mb-0">
            © {{ new Date().getFullYear() }} 书香阁 版权所有 | 京ICP备12345678号
          </div>
          <div class="flex space-x-4">
            <a href="#" class="text-gray-500 text-sm hover:text-primary">隐私政策</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">使用条款</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">网站地图</a>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI } from '@/api/order.js'
import ggbondImg from '@/assets/images/ggbond.png'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const orderDetail = ref(null)
const loading = ref(false)

// 计算购物车数量
const cartCount = computed(() => cartStore.cartCount)

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const goToCart = () => {
  router.push('/cart')
}

const goToBookDetail = (bookId) => {
  if (!bookId) return
  router.push(`/book/${bookId}`)
}

const goBack = () => {
  router.push('/orders')
}

const getStatusClass = (status) => {
  // 确保状态是数字类型
  const statusNum = parseInt(status)

  const statusClasses = {
    0: 'px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-800', // 待支付
    1: 'px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800',     // 已支付
    2: 'px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-800', // 已发货
    3: 'px-2 py-1 text-xs rounded-full bg-green-100 text-green-800',   // 已完成
    4: 'px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800'      // 已取消
  }
  return statusClasses[statusNum] || statusClasses[0]
}

const getStatusText = (status) => {
  // 确保状态是数字类型
  const statusNum = parseInt(status)

  const statusTexts = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '已完成',
    4: '已取消'
  }
  return statusTexts[statusNum] || '未知状态'
}

const getPaymentTypeText = (paymentType) => {
  if (!paymentType) return '-';
  const paymentTypes = {
    1: '支付宝',
    2: '微信支付',
    3: '银联支付'
  };
  return paymentTypes[paymentType] || '-';
};

const handleOrderAction = async (action, order) => {
  switch (action) {
    case 'pay':
      try {
        await ElMessageBox.confirm(
          `确认支付订单 ${order.orderNo}，金额 ¥${order.actualAmount.toFixed(2)} 吗？`,
          '确认支付',
          {
            confirmButtonText: '确认支付',
            cancelButtonText: '取消',
            type: 'info',
          }
        )
        // 调用支付API
        try {
          await orderAPI.payOrder(order.id, { paymentType: 1 }) // 默认使用支付宝支付(id=1)
          ElMessage.success('支付成功！')
          fetchOrderDetail() // 重新加载订单详情
        } catch (error) {
          console.error('支付失败:', error)
          ElMessage.error('支付失败，请稍后重试')
        }
      } catch {
        // 用户取消支付
      }
      break
    case 'confirm':
      try {
        await ElMessageBox.confirm(
          `确认收到订单 ${order.orderNo} 的商品了吗？`,
          '确认收货',
          {
            confirmButtonText: '确认收货',
            cancelButtonText: '取消',
            type: 'info',
          }
        )
        try {
          await orderAPI.confirmOrder(order.id)
          ElMessage.success('确认收货成功！')
          fetchOrderDetail() // 重新加载订单详情
        } catch (error) {
          console.error('确认收货失败:', error)
          ElMessage.error('确认收货失败，请稍后重试')
        }
      } catch {
        // 用户取消
      }
      break
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

  // 获取订单详情
const fetchOrderDetail = async () => {
  const orderId = parseInt(route.params.id)
  if (!orderId) {
    ElMessage.error('订单ID无效')
    router.push('/orders')
    return
  }

  loading.value = true
  try {
    const response = await orderAPI.getOrderDetail(orderId)
    console.log('订单详情响应:', response) // 添加日志查看响应结构

    // 检查响应结构并正确处理
    if (response.data && response.data.data) {
      // 处理标准响应结构
      const responseData = response.data.data

      // 处理不同的数据结构情况
      if (responseData.data && responseData.data.order) {
        // 嵌套的data.data.order结构
        const orderData = responseData.data
        orderDetail.value = {
          ...orderData.order,
          items: orderData.items || []
        }
      } else if (responseData.order) {
        // 直接的data.order结构
        orderDetail.value = {
          ...responseData.order,
          items: responseData.items || []
        }
      } else {
        // 尝试直接使用responseData作为订单数据
        // 这是一个后备方案，以防后端返回的结构与预期不同
        orderDetail.value = responseData
      }
    } else {
      ElMessage.error('订单不存在或数据结构不正确')
      console.error('订单详情数据结构不正确:', response)
      router.push('/orders')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败，请稍后重试')
    router.push('/orders')
  } finally {
    loading.value = false
  }
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.hover\:border-primary:hover {
  border-color: #FF6B8B !important;
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.bg-primary-dark {
  background-color: #E55A7A !important;
}

.hover\:bg-primary-dark:hover {
  background-color: #E55A7A !important;
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}

/* 订单详情卡片样式 */
.order-detail-card {
  transition: all 0.3s ease;
}

.order-detail-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 商品图片悬停效果 */
.order-item-image {
  transition: all 0.3s ease;
}

.order-item-image:hover {
  transform: scale(1.05);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .order-actions {
    flex-direction: column;
    gap: 0.5rem;
  }

  .order-actions button {
    width: 100%;
  }
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 面包屑导航样式 */
.breadcrumb-nav a {
  transition: color 0.2s ease;
}

.breadcrumb-nav a:hover {
  color: var(--primary);
}

/* 按钮悬停效果 */
.btn-hover:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
